# -*- coding: utf-8 -*-
"""
章节数据模型
"""

import uuid
import re
from typing import Dict, Any
from datetime import datetime


class Chapter:
    """章节模型类"""
    
    def __init__(self, title: str = "", content: str = "", order: int = 1):
        self.id = str(uuid.uuid4())
        self.title = title
        self.content = content
        self.order = order
        self.created_at = datetime.now()
        self.updated_at = datetime.now()
    
    def get_word_count(self) -> int:
        """获取章节字数（中文字符计数）"""
        # 移除空白字符，计算中文字符数
        text = re.sub(r'\s+', '', self.content)
        chinese_chars = re.findall(r'[\u4e00-\u9fff]', text)
        return len(chinese_chars)
    
    def get_character_count(self) -> int:
        """获取总字符数（包括标点符号）"""
        return len(self.content.strip())
    
    def update_content(self, content: str):
        """更新内容"""
        self.content = content
        self.updated_at = datetime.now()
    
    def update_title(self, title: str):
        """更新标题"""
        self.title = title
        self.updated_at = datetime.now()
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        return {
            "id": self.id,
            "title": self.title,
            "content": self.content,
            "order": self.order,
            "created_at": self.created_at.isoformat(),
            "updated_at": self.updated_at.isoformat(),
        }
    
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> 'Chapter':
        """从字典创建实例"""
        chapter = cls(
            title=data.get("title", ""),
            content=data.get("content", ""),
            order=data.get("order", 1)
        )
        chapter.id = data.get("id", str(uuid.uuid4()))
        
        # 设置时间
        if "created_at" in data:
            chapter.created_at = datetime.fromisoformat(data["created_at"])
        if "updated_at" in data:
            chapter.updated_at = datetime.fromisoformat(data["updated_at"])
        
        return chapter
    
    def __str__(self) -> str:
        return f"Chapter({self.title}, {self.get_word_count()}字)"
    
    def __repr__(self) -> str:
        return f"Chapter(id='{self.id}', title='{self.title}', order={self.order})" 